<template>
  <div id="app">
    <!-- <el-button>默认按钮</el-button> -->
    <MainPart v-if="$_.login"/>
    <Login @Login="$_.login = true" v-else/>
  </div>
</template>

<script>
import Login from './layout/login'
import MainPart from './layout/main'
import { EncryptRsa, DecryptRsa } from './utils/crypto'

export default {
  name: 'App',
  data() {
    return {
      login: false
    }
  },
  created() {
      const chatUser = JSON.parse(window.localStorage.getItem('chat-user'));
      
      if (chatUser) {
        const {
          username, userid, token, publicKey
        } = chatUser
        const privateKey = window.localStorage.getItem(`PRIVATE_${userid}`)
        if (!this.checkPair(privateKey, publicKey)) {
          this.$message.error('rsa密钥无效！消息无法接收,在个人资料内设置公钥和私钥')
          // return 
        }
        this.$_.initIo({
          username, userid, token
        },() => {this.$_.login = true})
      }
  },
  components: {
    Login,
    MainPart
  },
  methods: {
    checkPair(privateKey, publicKey) {
      if (privateKey&&publicKey) {
        try {
            const originMsg = 'ok';
            const encode = EncryptRsa(originMsg, publicKey);
            const decode = DecryptRsa(encode, privateKey);
            console.log(originMsg, decode)
            if (originMsg!=decode) {
                // callback(new Error('密钥对无法通过测试'))

                return false
            }
            return true
            // callback()
        }
        catch(e){
          return false
            // callback(new Error('密钥对无法通过测试'))
        }
          // return
      }
      return false
    }
  }
}
</script>

<style>
div {
  box-sizing: border-box;
}
body {
  margin: 0;
  padding: 0;
}
#app {
  width: 100%;
  height: 100vh;
}
</style>
